import {fetchMenuChildShow} from "@/api/home";
import router from "@/router";
import {Toast} from "vant";
import i18n from "@/locale/index";

export function dateFormat(date, fmt = 'YYYY-mm-dd HH:MM:SS') {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        }
    }
    return fmt;
}

// 深拷贝
export function deepClone(data) {
    let result
    if (typeof data === 'object') {
        if (Array.isArray(data)) {
            result = []
            for (let i = 0; i < data.length; i++) {
                result.push(deepClone(data[i]))
            }
        } else if (data === null) {
            result = null
        } else if (data.constructor === RegExp) {
            result = data
        } else if (data.constructor === Date) {
            result = data.getTime()
        } else {
            result = {}
            for (let i in data) {
                result[i] = deepClone(data[i])
            }
        }
    } else {
        result = data
    }
    return result
}

export function debounce(fn, wait = 2000, immediate = true) {
    let timer;
    return function () {
        if (timer) clearTimeout(timer);
        if (immediate) {
            // 如果已经执行过，不再执行
            var callNow = !timer;
            timer = setTimeout(() => {
                timer = null;
            }, wait)
            if (callNow) {
                fn.apply(this, arguments)
            }
        } else {
            timer = setTimeout(() => {
                fn.apply(this, arguments)
            }, wait);
        }
    }
}

// 压缩图片

export function compressImage(file) {
    return new Promise((resolve) => {
        //  大于1m压缩
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = e => {
            const src = e.target.result;
            const img = new Image();
            img.src = src
            img.onload = e => {
                let originWidth = img.width;
                let originHeight = img.height;
                let maxWidth = 1000;
                let maxHeight = 900;
                let targetWidth = originWidth;
                let targetHeight = originHeight;
                if (originWidth > maxWidth || originHeight > maxHeight) {
                    if (originWidth / originHeight > maxWidth / maxHeight) {
                        targetWidth = maxWidth
                        targetHeight = Math.floor(maxWidth * (originHeight / originWidth))
                    } else {
                        targetWidth = Math.floor(maxHeight * (originWidth / originHeight))
                        targetHeight = maxHeight;
                    }
                }
                const quality = 0.95;  // 默认图片质量为0.92
                // 生成canvas
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                // 创建属性节点
                const anw = document.createAttribute("width");
                anw.nodeValue = targetWidth;
                const anh = document.createAttribute("height");
                anh.nodeValue = targetHeight;
                canvas.setAttributeNode(anw);
                canvas.setAttributeNode(anh);
                // 铺底色 PNG转JPEG时透明区域会变黑色
                ctx.fillStyle = "#fff";
                ctx.fillRect(0, 0, targetWidth, targetHeight);
                ctx.drawImage(img, 0, 0, targetWidth, targetHeight);
                // quality值越小，所绘制出的图像越模糊
                const base64 = canvas.toDataURL('image/jpeg', quality); // 图片格式jpeg或webp可以选0-1质量区间
                // 返回base64转blob的值
                // 去掉url的头，并转换为byte
                const bytes = window.atob(base64.split(',')[1]);
                // 处理异常,将ascii码小于0的转换为大于0
                const ab = new ArrayBuffer(bytes.length);
                const ia = new Uint8Array(ab);
                for (let i = 0; i < bytes.length; i++) {
                    ia[i] = bytes.charCodeAt(i);
                }
                const filename = file.name
                file = new File([ia], filename, {type: 'image/jpeg'});
                resolve(file)
            }
        }
    })
}

// 设置资源菜单显示
export async function setResourcesShow(type) {
    // type 9 首页权限
    const res = await fetchMenuChildShow({type: type, productName: localStorage.getItem('productName')})
    if (res.code === 1) {
        const obj = {}
        res.data.forEach(i => {
            obj[i.resourcesFieldName] = i.status
        })
        return obj
    }
}
// 格式化金额
export function formatMoney(number, places, symbol, thousand, decimal) {
    number = number || 0;
    places = !isNaN(places = Math.abs(places)) ? places : 2;
    symbol = symbol !== undefined ? symbol : "$";
    thousand = thousand || ",";
    decimal = decimal || ".";
    var negative = number < 0 ? "-" : "",
        i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
}

// 流程跳转权限处理
export function processNext(flag, backRoutes) {
    /*
    * fang
    * */
    const {tm} = i18n.global
    let data = JSON.parse(localStorage.getItem('userInfoVerify'))
    if (flag) {
        const serveData = {
            ...data,
        }
        serveData[flag] = true
        data = serveData
        localStorage.setItem('userInfoVerify', JSON.stringify(serveData))
    }
    const {
        identityInfo,
        bankCardInfo,
        contactsInfo,
        operatorsInfo,
        personalInfo,
        workInfo,
        incomeProveInfo,
    } = data

    if (!identityInfo) {
        router.push({
            path: '/identityInfo',
            query: {
                backName: backRoutes
            }
        })
        return;
    }
    if (!personalInfo) {
        router.push({
            path: '/personalInfo',
            query: {
                backName: backRoutes
            }
        })
        return;
    }
    if (!workInfo) {
        router.push({
            path: '/workInfo',
            query: {
                backName: backRoutes
            }
        })
        return;
    }
    if (!contactsInfo) {
        router.push({
            path: '/contactsInfo',
            query: {
                backName: backRoutes
            }
        })
        return;
    }
    if (!operatorsInfo) {
        router.push({
            path: '/operatorsAuth',
            query: {
                backName: backRoutes
            }
        })
        return;
    }
    if (!bankCardInfo) {

        router.push({
            path: '/bankCardInfo',
            query: {
                backName: backRoutes
            }
        })
        return;
    }
    if (!incomeProveInfo) {
        router.push({
            path: '/supplementInfo',
            query: {
                backName: backRoutes
            }
        })
        return;
    }
    router.push({
        path: '/loanInfo',
        query: {
            backName: backRoutes
        }
    })
}
